package com.fzy.core;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.fzy.core.entity.Display;
import com.fzy.core.entity.EntityId;
import com.fzy.core.entity.EntityIdString;
import com.fzy.core.entity.MappingClass;
import com.opensymphony.webwork.interceptor.ServletRequestAware;
import com.opensymphony.webwork.util.TokenHelper;
import com.opensymphony.xwork.ActionContext;
import com.opensymphony.xwork.ActionSupport;

public class BaseAction extends ActionSupport implements ServletRequestAware, SelectQueryAware {
	/**
	 * 
	 */
	private static final long serialVersionUID = 2925430793127104593L;
	private static final Log log = LogFactory.getLog(BaseAction.class);
	protected HttpServletRequest request;
	protected boolean selected = false;
	
	public MappingClass getClassMapping(){
		ActionContext context = ActionContext.getContext();
		return (MappingClass)context.get("_c");
	}
	
	protected Map getRequestParams(){
		ActionContext context = ActionContext.getContext();
		Map requestParameters = (Map)context.getParameters();
		Map result = new HashMap();
		for (Iterator iterator = requestParameters.entrySet().iterator(); iterator.hasNext();) {
			Map.Entry entry = (Map.Entry) iterator.next();
			String[] value = (String[])entry.getValue();
			if(value != null && value.length > 0){
				result.put(entry.getKey(), value[0]);
			}
		}
		return result;
	}
	
	protected void validateToken() {
        Map session = ActionContext.getContext().getSession();
        synchronized (session) {
            if (!TokenHelper.validToken()) {
                addActionError(getText("error.duplicateSubmission"));
            }
        }
	}
	
	protected EntityId validateId(String idString, String clazz) {
		try {
			return validateIdAndGetEntity(idString, Class.forName(clazz));
		} catch (ClassNotFoundException e) {
			log.error(e.getMessage(), e);
		}
		return null;
	}

	protected Map validateId(String idString, MappingClass mappingClass) {
		Map entityObj = null;
		if (!StringUtils.isBlank(idString)) {
			Long id = null;
			try {
				long i = Long.parseLong(idString.trim());
				id = new Long(i);
			} catch (NumberFormatException e) {
				addActionError(getText("error.idError",
						new String[] { idString }));
			}
			if (id != null) {
				entityObj = U.getBaseService().get(mappingClass, id);
				if (entityObj == null) {
					addActionError(getText("error.entityMissing",
							new String[] { idString }));
				}
			}
		}
		if (entityObj == null) {
				entityObj = new HashMap();
		}

		return entityObj;
	}

	protected EntityIdString validateIdStringAndGetEntity(String idString, Class clazz) {
		return validateIdStringAndGetEntity(idString, "id", clazz);
	}

	protected EntityIdString validateIdStringAndGetEntity(String idString, String idProperty, Class clazz) {
		Object entityObj = null;
		if (!StringUtils.isBlank(idString)) {
			idString = idString.trim();
				entityObj = U.getBaseService().getByIdString(clazz, idProperty, idString);
				if (entityObj == null) {
					addActionError(getText("error.entityMissing",
							new String[] { idString }));
				}
		}
		return (EntityIdString)entityObj;
	}

	protected EntityId validateIdAndGetEntity(String idString, Class clazz) {
		Object entityObj = null;
		if (!StringUtils.isBlank(idString)) {
			Long id = null;
			try {
				long i = Long.parseLong(idString.trim());
				id = new Long(i);
			} catch (NumberFormatException e) {
				addActionError(getText("error.idError",
						new String[] { idString }));
			}
			if (id != null) {
				entityObj = U.getBaseService().get(clazz, id);
				if (entityObj == null) {
					addActionError(getText("error.entityMissing",
							new String[] { idString }));
				}
			}
		}
		return (EntityId) entityObj;
	}
	
	protected Object newEntity(Class clazz){
		Object entityObj = null;
		try {
			entityObj = clazz.newInstance();
		} catch (InstantiationException e) {
			log.error(e.getMessage(), e);
		} catch (IllegalAccessException e) {
			log.error(e.getMessage(), e);
		}
		return entityObj;
	}
	
	protected void validateSelectQuery(Class clazz){
		String mode = request.getParameter("_m");
		String selectValue = request.getParameter("_sv");
		if("1".equals(mode) && !StringUtils.isBlank(selectValue)){
			Object e = validateIdAndGetEntity(selectValue, clazz);
			if(e == null){
				log.error("Cannot find entity ["+clazz+"] by id ["+selectValue+"].");
			}
			if(e != null && e instanceof Display){
				Display d = (Display)e;
				String displayName = d.display();
				request.setAttribute("_sv2", displayName == null ? "" : displayName);
				selected = true;
			}
		}
	}

	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}

	public boolean isSelected() {
		return selected;
	}

}
